//
//  SeekoArticleViewController.m
//  MokoAPP
//
//  Created by 현식 강 on 11. 8. 1..
//  Copyright 2011 아이온. All rights reserved.
//

#import "SeekoArticleViewController.h"
#import "MokoAppDelegate.h"
#import "SeekoArticleTableViewController.h"
#import "SeekoBoardListTableViewController.h"
#import "SeekoArticleContentWebView.h"
#import "GTMNSString+HTML.h"
#import "MemoWriteViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation SeekoArticleViewController
@synthesize contentWebView,
            deleteButton,
            modifyButton,
            commentContentTextView,
            commentRegistrationButton,
            userNameLabel,
            userLevelLabel,
            articleNo,
            link,
            boardId,
            viewDateLabel,
            isNoticeArticle,
            userId,
            articleDate;
@synthesize articleTitle, articleContent, articleLinks, articleImages;

-(void)finishLoading:(NSData *)data {
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"삭제 완료" message:@"글이 삭제 되었습니다." delegate:self cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
    alert.tag = 1;
    [alert show];
    [alert release];
    NSArray* viewControllers = self.navigationController.viewControllers;
    int count = [viewControllers count];
    SeekoBoardListTableViewController* boardListController = [viewControllers objectAtIndex:count-2];
    [boardListController loadFirstPage];
    [parentController.navigationController popViewControllerAnimated:YES];
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if( alertView.tag == 1 )
        [self.navigationController popViewControllerAnimated:YES];
    else if (alertView.tag == 1000 ) {
        if( buttonIndex == 1 ) {
            GET_APPDELEGATE;
            [[self.view.superview firstAvailableUIViewController].navigationController presentModalViewController:delegate.loginViewController animated:YES];
        }
    }
}
- (IBAction)deleteAction:(id)sender {
    GET_APPDELEGATE;
    NSString* poststr = [NSString stringWithFormat:@"id=%@&no=%@", boardId, articleNo];
    NSData* data = [poststr dataUsingEncoding:EUC_KR];
    [delegate.httpClient requestURL:[NSString stringWithFormat:@"%@/zboard4/delete_ok.php", delegate.configVO.siteHostAddress, boardId, articleNo] httpMethod:@"POST" bodyData:data isMultiPart:NO boundary:nil target:self selector:@selector(finishLoading:)];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil link:(NSString*)_link parentController:(SeekoArticleTableViewController *)_parentController;
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.link = _link;
        NSDictionary* dic = [link parseQueryString];
        self.boardId = [dic objectForKey:@"id"];
        self.articleNo = [dic objectForKey:@"no"];
        
                // 등록 버튼 이미지 설정
        parentController = _parentController;
        // Do any additional setup after loading the view from its nib.
        //[contentLabel setFrame:CGRectMake(contentLabel.frame.origin.x, contentLabel.frame.origin.y, 285, 3000)];
        // 최초에 수정, 삭제, 댓글 등록 버튼, 댓글 등록 텍스트 뷰는 감춰놓는다.
    }
    return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSArray* subviews = [self.view subviews];
    for( UIView* views in subviews ) 
        [views resignFirstResponder];
}
-(BOOL)canWriteComment {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    NSDate* date = [dateFormatter dateFromString:parentController.articleDate];
    NSDate* today = [NSDate date];
    NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    int result = 
    [[gregorian components:NSDayCalendarUnit fromDate:date toDate:today options:0] day];
    [dateFormatter release];
    [gregorian release];
    
    return result <= 30 || isNoticeArticle == YES;
}

- (IBAction)hideKeyboard:(id)sender {
    NSArray* subviews = [self.view subviews];
    for( UIView* views in subviews ) 
        [views resignFirstResponder];
}
- (IBAction)commentRegistration:(id)sender {
    GET_APPDELEGATE;
    
    if( [self canWriteComment] == NO ) {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"30일이 지난 글은 댓글을 달 수 없습니다" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
        [alertView show];
        [alertView release];
    } else {
        if( [delegate.httpClient didLogin] == YES ) {
            if( [commentContentTextView.text length] > 0 ) {
                NSString* body = @"";
                // 댓글 낙인 사용시에만 모꼬가 들어가고 나머지는 안 들어감.
                if( [delegate.configVO.useCommentSignature boolValue] == YES ) {
                    body = [NSString stringWithFormat:@"id=%@&no=%@&memo=%@%@", boardId, articleNo, [commentContentTextView.text stringByAddingPercentEscapesUsingEncoding:EUC_KR], [[NSString stringWithFormat:@" %@", delegate.configVO.commentSignature] stringByAddingPercentEscapesUsingEncoding:EUC_KR]];
                }
                else {
                    body = [NSString stringWithFormat:@"id=%@&no=%@&memo=%@", boardId, articleNo, [commentContentTextView.text stringByAddingPercentEscapesUsingEncoding:EUC_KR]];
                }
                commentContentTextView.text = @"";
                NSData* data = [body dataUsingEncoding:EUC_KR];
                [delegate.httpClient requestURL:[NSString stringWithFormat:@"%@/zboard4/comment_ok.php", delegate.configVO.siteHostAddress] httpMethod:@"POST" bodyData:data isMultiPart:NO boundary:nil target:(id)[self.view.superview firstAvailableUIViewController] selector:@selector(reloadAllData)];
                // 댓글이 올라갈 경우 맨 밑으로 스크롤을 내린다.
                [parentController.tableView setContentOffset:CGPointMake(0, parentController.tableView.contentSize.height)];
            } else {
                UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"최소 1글자 이상의 댓글을 입력 해야 됩니다." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"확인", nil];
                [alertView show];
                [alertView release];
            }
            // 댓글창 키보드 제거
            for( UIView* subViews in [self.view subviews] )
                [subViews resignFirstResponder];
        } else {
            // 로그인 경고 띄우기
            [self showLoginView];
        }
    }
}

- (void)dealloc
{
    [articleDate release];
    [userId release];
    [articleLinks release];
    [articleImages release];
    [articleContent release];
    [articleTitle release];
    [boardId release];
    [articleNo release];
    [link release];
    [userNameLabel release];
    [userLevelLabel release];
    [commentRegistrationButton release];
    [deleteButton release];
    [modifyButton release];
    [commentContentTextView release];
    [contentWebView release];
    [viewDateLabel release];
    [backgroundColorLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    self.view.autoresizesSubviews = YES;
    //viewDateLabel.textColor = [UIColor whiteColor];
    viewDateLabel.textAlignment = UITextAlignmentRight;
    //userNameLabel.textColor = [UIColor whiteColor];
    //userNameLabel.textColor = RGB(255, 255, 153);

    [backgroundColorLabel removeFromSuperview];
    [self.view insertSubview:backgroundColorLabel atIndex:0];
    
    // 장터는 수정/삭제 불가
    if( [boardId isEqualToString:@"buysell"] ) {
        modifyButton.hidden = YES;
        deleteButton.hidden = YES;
    }
    
    commentContentTextView.layer.cornerRadius = 7;
    commentContentTextView.clipsToBounds = YES;
    commentContentTextView.placeholderColor = [UIColor blackColor];
    commentContentTextView.font = [UIFont fontWithName:@"Helvetica" size:13.0f];
    UILongPressGestureRecognizer* gr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(nameLongClick:)];
    [userNameLabel addGestureRecognizer:gr];
    [gr release];
    contentWebView.tableController = parentController;
    
    modifyButton.hidden = YES;
    deleteButton.hidden = YES;        
    // 지정된 높이에 맞게 계속 늘어남
    
    self.commentContentTextView.delegate = self;
    
    commentContentTextView.placeholder = @"댓글을 등록하세요";
    contentWebView.delegate = contentWebView;
    
    firstCommentContentTextViewFrame = commentContentTextView.frame;
    contentWebView.layer.cornerRadius = 7;
    viewDateLabel.text = articleDate;
    
        
}
-(void)nameLongClick:(id)sender {
    UILongPressGestureRecognizer* gr = (UILongPressGestureRecognizer*)sender;
    if ([gr state] == UIGestureRecognizerStateBegan) {
        UIActionSheet* sheet = [[UIActionSheet alloc] init];
        sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
        sheet.delegate = self;
        if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone ) {
            sheet.cancelButtonIndex = 0;
            [sheet addButtonWithTitle:@"취소"];
        }
        [sheet addButtonWithTitle:@"회원 정보"];
        sheet.title = [NSString stringWithFormat:@"선택된 회원 %@ 님", userNameLabel.text];
        GET_APPDELEGATE;
        if( delegate.httpClient.isLogin == YES ) 
            [sheet addButtonWithTitle:@"쪽지 보내기"];
        [sheet addButtonWithTitle:@"이름으로 검색"];
        sheet.tag = 10;
        [sheet showFromTabBar:parentController.tabBarController.tabBar];
        [sheet release];
    }
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 댓글 액션 시트
    if( actionSheet.tag == 10 ) {
        // 회원 정보
        if(buttonIndex == actionSheet.cancelButtonIndex + 1) {
            GET_APPDELEGATE;
            NSString* addr = [NSString stringWithFormat:@"%@/zboard4/view_info2.php?member_no=%@", delegate.configVO.siteHostAddress, userId];
            
            [delegate.httpClient requestURL:addr httpMethod:@"GET" bodyData:nil isMultiPart:NO boundary:nil target:parentController selector:@selector(memberInfo:)];
        }
        // 이름으로 검색
        else if( actionSheet.numberOfButtons-1 == buttonIndex ) {
            NSArray* controllers = parentController.navigationController.viewControllers;
            SeekoBoardListTableViewController* list = [controllers objectAtIndex:[controllers count]-2];
            [list.searchDisplayController setActive:YES];
            [list searchDisplayController:nil shouldReloadTableForSearchScope:0];
            list.searchDisplayController.searchBar.text = [userNameLabel.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            [list searchBarSearchButtonClicked:list.searchDisplayController.searchBar];
            [parentController.navigationController popViewControllerAnimated:YES];
        }  
        // 쪽지 보내기
        else if( buttonIndex != 0 && buttonIndex != -1 ){
            
            MemoWriteViewController* memoViewController;
            if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
                memoViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController" bundle:nil];
            else
                memoViewController = [[MemoWriteViewController alloc] initWithNibName:@"MemoWriteViewController-iPad" bundle:nil];
            memoViewController.toUserId = userId;
            memoViewController.toUserName = userNameLabel.text;
            memoViewController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [parentController presentModalViewController:memoViewController animated:YES];
            [memoViewController release];
        }
    }
}
- (void)viewDidUnload
{
    [userNameLabel release];
    userNameLabel = nil;
    [userLevelLabel release];
    userLevelLabel = nil;
    [deleteButton release];
    deleteButton = nil;
    [modifyButton release];
    modifyButton = nil;
    [viewDateLabel release];
    viewDateLabel = nil;
    [backgroundColorLabel release];
    backgroundColorLabel = nil;
    [commentRegistrationButton release];
    commentRegistrationButton = nil;
    [commentContentTextView release];
    commentContentTextView = nil;
    [contentWebView release];
    contentWebView = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    GET_APPDELEGATE;
    if( [delegate.httpClient didLogin] == YES ) {
        // 댓글 작성시 댓글 위치에 스크롤을 맞춘다.
        [parentController.tableView setContentOffset:CGPointMake(0, textView.frame.origin.y)];
        return YES;
    }
    else {
        [self showLoginView];
        return NO;
    }
}
-(void)textViewDidChange:(UITextView *)textView {
    if( [textView.text length] > 0 ) {
        if( commentContentTextView.contentSize.height > firstCommentContentTextViewFrame.size.height ) {
            CGFloat height = textView.contentSize.height;
            CGRect frame;
            CGRect textViewFrame = textView.frame;
            float addHeight = height - textView.frame.size.height;
            
            for( UIView* subview in [self.view subviews] ) {
                // 댓글 뷰보다 아래에 있으면 늘어난 높이만큼 y값 증가
                if( subview.hidden == NO && (CGRectGetMaxY(subview.frame)> CGRectGetMaxY(textViewFrame)) ) {
                    frame = subview.frame;
                    frame.origin.y += addHeight;
                    subview.frame = frame;
                }
            }
            frame = textView.frame;
            frame.size = textView.contentSize;
            textView.frame = frame;
            float maxHeight = 0;
            for( UIView* subview in [self.view subviews] ) {
                if( subview.hidden == NO ) {
                    maxHeight = MAX(maxHeight, CGRectGetMaxY(subview.frame));
                }
            }
            frame = self.view.frame;
            frame.size.height = maxHeight + 10;
            self.view.frame = frame;
            parentController.tableView.tableHeaderView = self.view;
            [parentController.tableView setContentOffset:CGPointMake(0, textView.frame.origin.y + textView.frame.size.height - 80)];
        }
    }
}
- (void)showLoginView {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"로그인이 필요합니다." message:@"로그인 하시겠습니까?" delegate:self cancelButtonTitle:@"취소" otherButtonTitles:@"확인", nil];
    alertView.tag = 1000;
    [alertView show];
    [alertView release];
}
// 수정 메소드
- (IBAction)modify:(id)sender {
    NSRange range = NSMakeRange([articleContent indexOf:@"<"], [articleContent indexOf:@">"]+1);
    NSString* convertContent = articleContent;
    if( range.location != NSNotFound )
        convertContent = [articleContent stringByReplacingOccurrencesOfString:[articleContent substringWithRange:range] withString:@""];
    convertContent = [[[[[convertContent substringToIndex:[convertContent lastIndexOf:@"</td>"]] stringByReplacingOccurrencesOfString:@"<br>" withString:@"\n"] stringByReplacingOccurrencesOfString:@"\r" withString:@""] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] gtm_stringByUnescapingFromHTML];
    int commentIndex = [convertContent lastIndexOf:@"<!--"];
    if( commentIndex != NSNotFound ) {
        convertContent = [convertContent substringToIndex:commentIndex];
    }
    int alink = [[contentWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('links').getElementsByTagName('a').length"] intValue];
    NSString* href = @"";
    if( alink == 1 ) {
        href = [contentWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('links').getElementsByTagName('a')[0].href"];
    }
    NSDictionary* vo = [[[NSDictionary alloc] initWithObjectsAndKeys:
                         articleNo,@"no",
                         boardId, @"id",
                         articleTitle, @"title",
                         convertContent, @"content", href, @"link",  nil] autorelease];
    WriteViewController* writeViewController = nil;
    if( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone )
        writeViewController = [[WriteViewController alloc] initWithNibName:@"WriteAndModifyViewController" bundle:[NSBundle mainBundle] isModify:YES vo:vo];
    else
        writeViewController = [[WriteViewController alloc] initWithNibName:@"WriteAndModifyViewController-iPad" bundle:[NSBundle mainBundle] isModify:YES vo:vo];
    [[self.view.superview firstAvailableUIViewController].navigationController pushViewController:writeViewController animated:YES];
}

@end
